package nl.hva.three2learn.dao;

import java.util.List;

import nl.hva.three2learn.model.Answer;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public final class AnswerDaoImpl implements AnswerDao {

	@Autowired
	private SessionFactory sessionFactory;
	
	@Override
	public Answer findById(long answerId) {
		
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		
		Query q = session.createQuery("from Answer a where a.id = :id");
		q.setLong("id", answerId);
		
		Object result = q.uniqueResult();
		
		session.getTransaction().commit();
		
		if (result == null)
			return null;
		
		return (Answer) result;
	}
	
	@Override
	public void save(Answer answer) {
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		session.saveOrUpdate(answer);
		session.getTransaction().commit();
	}
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public List<Answer> findAllAnswers() {
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		
		Query q = session.createQuery("from Answer");
		
		List<Answer> answers = q.list();
		
		session.getTransaction().commit();
		
		return answers;
	}
}
